package dd.server;

import java.util.ArrayList;

import org.w3c.dom.NamedNodeMap;

import server.ClientState;
import server.Server;
import xml.Message;
import dd.model.Edge;
import dd.model.Event;
import dd.model.serverModel;

public class addEdgeResponseController {

	public Message process(ClientState client, Message request) {
		// serverModel sm = serverModel.getInstance();
		// Event e = sm.getEvent();
		NamedNodeMap map = request.contents.getFirstChild().getAttributes();
		// get information
		String eventId = map.getNamedItem("id").getNodeValue();
		Event event = serverModel.getInstance().getEventByEventId(eventId);
		if (event == null) {
			event = new Event();
		}
		// event.setLeftEdges()
		String leftt = map.getNamedItem("left").getNodeValue();
		int left = Integer.parseInt(leftt);
		String rightt = map.getNamedItem("right").getNodeValue();
		int right = Integer.parseInt(rightt);
		String heightt = map.getNamedItem("height").getNodeValue();
		int height = Integer.parseInt(heightt);
		System.out.println("received: " + leftt + " " + rightt + " " + heightt);
		ArrayList<Edge> ledge = event.getedgelist();
		Edge edge = new Edge();
		edge.setEdge(left, right, height);
		ledge.add(edge);
		event.setedgelist(ledge);
		// Construct message reflecting state
		String xmlString = Message.responseHeader(request.id()) + "<addEdgeResponse id='" + eventId + "' left='"
				+ leftt + "' right='" + rightt + "' height='" + heightt + "'>" + "</addEdgeResponse></response>";
		Message m = new Message(xmlString);
		// send this response to all the client
		for (String id : Server.ids()) {
			if (!id.equals(client.id()) && Server.ids().contains(id)) {
				Server.getState(id).sendMessage(m);
			}
		}
		// if mode is roundRobin, activate the next client (TODO: 2 clients right now, simply enable the another one)
		if (event.getType().equals("roundRobin")) {
			String turnMessage = Message.responseHeader(request.id())
					+ "<turnResponse completed='false'></turnResponse></response>";
			for (String id : Server.ids()) {
				if (!id.equals(client.id()) && Server.ids().contains(id)) {
					Server.getState(id).sendMessage(new Message(turnMessage));
				}
			}
		}

		// send this response back to the client which sent us the request.
		return m;
	}
}
